<?php

namespace app\model;

use think\Model;

class DistributionSettlement extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'distribution_settlement';
    // 设置当前模型主键
    protected $pk = 'id';

    // 根据条件获取分页数据
    public function getPagingDataByWhere($where = [], $page = 1, $limit = 10, $fields = 'id', $order = 'id desc')
    {
        $offset = ($page - 1) * $limit;

        $total = $this::where($where)->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $totalPage = ceil($total / $limit);

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();
        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }


    // 根据条件获取分页数据
    public function getPagingDataByWhereAdmin($where = [], $page = 1, $limit = 10, $fields = 'id', $order = 'id desc')
    {
        $offset = ($page - 1) * $limit;

        $query = $this::alias('ds')
            ->join('ly_responsibility_person rp', 'ds.distributor_id = rp.id')
            ->join('ly_company c', 'c.id = rp.company_id')
            ->where($where);

        $total = $query->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $totalPage = ceil($total / $limit);

        $data = $query->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();
        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    /**
     * 新增/更新
     * 
     * @dateTime 2022/08/24
     * @author zhixiang0215@126.com
     * @param array $params
     * @return int
     */
    public function edit($params)
    {
        if (empty($params['id'])) {
            $data = $this::create($params);
            return $data->id;
        }
        $this::update($params);
        return $params['id'];
    }

    /**
     * 根据条件获取数据
     * 
     * @dateTime 2022/09/26
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @return array
     */
    public function getInfoByWhere(array $where = [], string $fields = 'id')
    {
        $data = $this::where($where)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 根据条件获取数据
     * 
     * @dateTime 2022/09/26
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @return array
     */
    public function getDataByWhere(array $where = [], string $fields = 'id')
    {
        $data = $this::where($where)->field($fields)->select();
        return $data ? $data->toArray() : [];
    }
}